﻿using System.Drawing;
using System.IO;
using System.Text;
using MultiThumbnail.Properties;

namespace MultiThumbnail.Converters
{
    [Extension("TXT;INI;INF;XML")]
    class TxtThumbConverter : ThumbConverter
    {
        private const int MaxFileLength = 10000;

        public override bool CreateMiniature(Stream fileStream, string resultPath)
        {
            var text = ReadText(fileStream);
            using (var result = new Bitmap(ConverterSettings.ImageSize.Width, ConverterSettings.ImageSize.Height))
            {
                using (var graphics = Graphics.FromImage(result))
                {
                    using (var font = new Font(FontFamily.GenericSansSerif, 14))
                    {
                        graphics.Clear(Color.White);
                        graphics.DrawString(text, font, Brushes.Black, new RectangleF(0, 0, ConverterSettings.ImageSize.Width, ConverterSettings.ImageSize.Height));
                    }
                }
                result.Save(resultPath);
            }
            return true;
        }

        private static string ReadText(Stream fileStream)
        {
            using (var streamReader = new StreamReader(fileStream, Encoding.GetEncoding(Settings.Default.DefaultTextEncodingCodePage)))
            {
                if (fileStream.Length < MaxFileLength)
                    return streamReader.ReadToEnd();
                var buffer = new char[MaxFileLength];
                streamReader.ReadBlock(buffer, 0, MaxFileLength);
                return new string(buffer);
            }
        }
    }
}
